from sqlalchemy.orm import Session
from fastapi import HTTPException
from models.nurse_model import MedicalCaseModel
from datetime import datetime
from schemas.nurse_schema import MedicalCaseCreate, ListMedicalCase, ItemMedicalCase,MedicalCaseUpdate


def get_medical_case(db: Session, id: int):
  return db.query(MedicalCaseModel).filter(MedicalCaseModel.id == id).first()


def get_medical_cases(db: Session, case: ListMedicalCase):
  create_time = case.create_time
  pageSize = case.pageSize
  pageIndex = case.pageIndex
  skip = (pageIndex - 1) * pageSize
  query = db.query(MedicalCaseModel)
  # 添加 patient_id 过滤条件
  query = query.filter(MedicalCaseModel.patient_id == case.patient_id, MedicalCaseModel.shop_id == case.shop_id, MedicalCaseModel.status != 0)

  if create_time:
    query = query.filter(MedicalCaseModel.create_time >= create_time)

  # 默认按创建时间倒序排序
  query = query.order_by(MedicalCaseModel.create_time.desc())

  # 查询当前页数据
  total = query.count()
  items = query.offset(skip).limit(pageSize).all()
  # 将 SQLAlchemy 模型转换为 Pydantic 模型
  # items_schema = [ItemMedicalCase.from_orm(item) for item in items]
  items_schema = []
  for item in items:
    # 创建字典表示
    item_dict = {
      "id": str(item.id),  # 确保 ID 转换为字符串
      "shop_id":item.shop_id,
      "case_images": item.case_images,
      "patient_id": item.patient_id,
      "patient_name": item.patient_name,
      "description": item.description,
      "diagnosis": item.diagnosis,
      "treatment_plan": item.treatment_plan,
      "create_time": item.create_time,
      "update_time": item.update_time,
      "doctor_id": item.doctor_id,
      "doctor_name": item.doctor_name,
      "deleted_at": item.deleted_at,
      "status": item.status
    }
    # 使用模型验证数据
    items_schema.append(ItemMedicalCase(**item_dict))
  # 计算总页数
  total_pages = (total + pageSize - 1) // pageSize
  return {
    "data": items_schema,
    "total": total,
    "pageIndex": pageIndex,
    "pageSize": pageSize,
    "totalPages": total_pages
  }


def create_medical_case(db: Session, case: MedicalCaseCreate):
  case_data = case.model_dump(exclude_none=True)
  # 排除时间字段，让数据库使用默认值
  case_data.pop('created_time', None)
  case_data.pop('updated_time', None)
  case_data.pop('deleted_at', None)

  db_case = MedicalCaseModel(**case_data)
  db.add(db_case)
  db.commit()
  db.refresh(db_case)
  # 将 id 转换为字符串，以匹配 Pydantic 模型的期望类型
  db_case.id = str(db_case.id)
  return db_case


def del_medical_case(db: Session, id: int):
  # 查询要删除的病例
  db_case = db.query(MedicalCaseModel).filter(MedicalCaseModel.id == id, MedicalCaseModel.status != 0).first()

  if db_case is None:
    raise HTTPException(status_code=404, detail="护理病例不存在")

  # 软删除
  db_case.status = 0
  db_case.deleted_at = datetime.now()
  db.commit()
  return {"message": "删除成功"}


def update_medical_case(db: Session, case: MedicalCaseUpdate):
  try:
    # 将字符串 ID 转换为整数进行数据库查询
    case_id = int(case.id)
  except ValueError:
    raise HTTPException(status_code=400, detail="无效的病例ID")
  item = db.query(MedicalCaseModel).filter(MedicalCaseModel.id == case_id).first()
  if item is None:
    raise HTTPException(status_code=404, detail="护理病例不存在")

  # 获取前端实际提供的字段（排除未设置的字段）
  update_data = case.model_dump(exclude_unset=True)
  # 移除 id 字段，因为它不应该被更新
  update_data.pop('id', None)
  # 排除时间字段，让数据库使用默认值
  update_data.pop('created_time', None)
  update_data.pop('updated_time', None)
  update_data.pop('deleted_at', None)
  # 处理状态和删除时间的关系
  if 'status' in update_data:
    if update_data['status'] == 1:
      item.deleted_at = None
    elif update_data['status'] == 0:
      item.deleted_at = datetime.now()

  # 仅更新提供的字段
  for field, value in update_data.items():
    setattr(item, field, value)

  # 更新时间
  item.updated_time = datetime.now()
  db.commit()
  db.refresh(item)
  
  # 将 SQLAlchemy 模型转换为 Pydantic 模型
  item_data = ItemMedicalCase.from_orm(item)
  
  return {"message": "更新成功", "data": item_data}
  
  # return {
  #   "message": "更新成功",
  #   "data": {
  #     "id": item.id,
  #     "patient_id": item.patient_id,
  #     "patient_name": item.patient_name,
  #     "description": item.description,
  #     "case_images": item.case_images,
  #     "diagnosis": item.diagnosis,
  #     "treatment_plan": item.treatment_plan,
  #     "create_time": item.create_time,
  #     "update_time": item.update_time,
  #     "doctor_id": item.doctor_id,
  #     "doctor_name": item.doctor_name,
  #     "deleted_at": item.deleted_at,
  #     "status": item.status
  #   }
  # }